package com.huiruan.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiruan.dto.UserDTO;
import com.huiruan.entity.SysRole;
import com.huiruan.entity.SysUser;
import com.huiruan.mapper.SysUserMapper;
import com.huiruan.service.SysUserService;
import com.huiruan.utils.JwtUtil;
import com.huiruan.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * PC用户服务实现类
 */

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiruan.entity.SysUser;
import com.huiruan.mapper.SysUserMapper;
import com.huiruan.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * PC用户服务实现
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Override
    public SysUser getByUsername(String username) {
        return lambdaQuery().eq(SysUser::getUserName, username).one();
    }

    @Override
    public Boolean removeUserByIds(Long[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveUser(UserDTO userDto) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userDto, sysUser);
        sysUser.setDelFlag("0");
        sysUser.setCreateBy(userDto.getUserName());
        sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
        baseMapper.insert(sysUser);
        //todo 如果角色为空，赋默认角色
        if (CollUtil.isEmpty(userDto.getRole())) {
            // 获取默认角色编码
            //String defaultRole = ParamResolver.getStr("USER_DEFAULT_ROLE");
            // 默认角色
//            SysRole sysRole = sysRoleService
//                    .getOne(Wrappers.<SysRole>lambdaQuery().eq(SysRole::getRoleCode, defaultRole));
//            userDto.setRole(Collections.singletonList(sysRole.getRoleId()));
        }

        //todo 插入用户角色关系表
//        userDto.getRole().forEach(roleId -> {
//            SysUserRole userRole = new SysUserRole();
//            userRole.setUserId(sysUser.getUserId());
//            userRole.setRoleId(roleId);
//            sysUserRoleMapper.insert(userRole);
//        });
        return Boolean.TRUE;
    }

    @Override
    @Transactional
    public Boolean updateUser(UserDTO userDto) {
        // 更新用户表信息
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userDto, sysUser);
        sysUser.setUpdateTime(LocalDateTime.now());
        if (StrUtil.isNotBlank(userDto.getPassword())) {
            sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
        }
        this.updateById(sysUser);

        // 更新用户角色表
        if (Objects.nonNull(userDto.getRole())) {
            //todo 删除用户角色关系
            /**
            sysUserRoleMapper
                    .delete(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userDto.getUserId()));
            userDto.getRole().forEach(roleId -> {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(sysUser.getUserId());
                userRole.setRoleId(roleId);
                sysUserRoleMapper.insert(userRole);
            });
**/

        }

        return Boolean.TRUE;
    }

    @Override
    public Result updateUserInfo(UserDTO userDto) {
        SysUser user = JwtUtil.getPcUserInfo();
        SysUser sysUser = new SysUser();
        sysUser.setPhone(userDto.getPhone());
        sysUser.setId(user.getId());
        sysUser.setAvatar(userDto.getAvatar());
        sysUser.setNickName(userDto.getNickName());
        sysUser.setUserName(userDto.getUserName());
        sysUser.setEmail(userDto.getEmail());
        return Result.success(this.updateById(sysUser));
    }

    @Override
    public IPage getUsersWithRolePage(Page page, UserDTO userDTO) {
        return baseMapper.getUsersPage(page, userDTO);
    }
}
